﻿using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Forms.Integration;
using System.Windows.Interop;
using NLog;
using Point = System.Drawing.Point;
using Size = System.Drawing.Size;
using UserControl = System.Windows.Forms.UserControl;

namespace Byond.Vst
{
	public partial class WinFormsEditor : UserControl
	{
		private readonly ElementHost _wpfElementHost;
		private readonly Logger _logger;

		public WinFormsEditor()
		{
			_wpfElementHost = new ElementHost();
			SuspendLayout();
			// 
			// _wpfElementHost
			// 
			_wpfElementHost.Location = new Point(0, 0);
			_wpfElementHost.Name = "_wpfElementHost";
			_wpfElementHost.Dock = DockStyle.Fill;
			_wpfElementHost.TabIndex = 0;
			_wpfElementHost.Text = "_wpfElementHost";

			// 
			// WinFormsEditor
			// 
			//AutoScaleDimensions = new SizeF(6F, 13F);
			//AutoScaleMode = AutoScaleMode.Font;
			Controls.Add(_wpfElementHost);
			Name = "WinFormsEditor";
			Size = new Size(1200, 750);
			ResumeLayout(false);
		}

		private bool _isInitialized;

		[DllImport("user32.dll")]
		public static extern IntPtr SetParent(IntPtr child, IntPtr newParent);

		private const UInt32 DLGC_WANTARROWS = 0x0001;
		private const UInt32 DLGC_WANTTAB = 0x0002;
		private const UInt32 DLGC_WANTALLKEYS = 0x0004;
		private const UInt32 DLGC_HASSETSEL = 0x0008;
		private const UInt32 DLGC_WANTCHARS = 0x0080;
		private const UInt32 WM_GETDLGCODE = 0x0087;

		public void Open(IntPtr hWnd)
		{
			if (!_isInitialized)
			{
				_isInitialized = true;
	
				//var source = HwndSource.FromHwnd(hWnd);
				//var source = PresentationSource.FromVisual(_wpfElementHost.Child) as HwndSource;
				//source.AddHook(WndProc);
			}
			SetParent(Handle, hWnd);
			Show();
		}

		protected override void WndProc(ref Message m)
		{
			var wm = (WM)(m.Msg);
			//_logger.Info("WinForms Msg: " + m.Msg + " - " + wm);
			base.WndProc(ref m);
		}

		private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam, ref bool handled)
		{
			if (msg == WM_GETDLGCODE)
			{
				handled = true;
				return new IntPtr(DLGC_WANTCHARS | DLGC_WANTARROWS | DLGC_HASSETSEL);
			}
			
			return IntPtr.Zero;
		}

		//public void Close()
		//{
		//    //_wpfElementHost.Child = null;
		//    //Dispose();
		//}

		public void SetContent(FrameworkElement frameworkElement)
		{
			if (_wpfElementHost.Child == frameworkElement)
				return;

			// HACK
			if (frameworkElement.Parent is ContentControl)
				(frameworkElement.Parent as ContentControl).Content = null;

			_wpfElementHost.Child = frameworkElement;
		}
	}
}